package com.example.springboot.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 获取ip地址
 *
 * @Author:ChenZhangKun
 * @Date: 2021/8/1 18:31
 */
public class GetIPUtils {
    public static String getIp() {
        try {
            // 万维网地址
            String path = "http://www.net.cn/static/customercare/yourip.asp";
            // 构件链接
            URL url = new URL(path);
            // 打开连接
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestProperty("contentType", "GBK"); // 设置url中文参数编码

            urlConnection.setConnectTimeout(5 * 1000);// 请求的时间

            urlConnection.setRequestMethod("GET");// 请求方式
            // 拿到输入流
            InputStream inputStream = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            StringBuilder builder = new StringBuilder();
            String content = null;
            while ((content = bufferedReader.readLine()) != null) {
                builder.append(content);
            }
            // 创建集合
            List<String> list = new ArrayList<>();
            // 用正则表达式提取String字符串中的IP地址
            String regEx = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
            String str = builder.toString();
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(str);
            while (m.find()) {
                String result = m.group();
                list.add(result);
            }
            if (list.size() > 0) {
                return list.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
